import React from 'react'
import { connect } from 'dva'
import PageHeaderLayout from 'components/Layout/PageHeaderLayout'
import { Page } from 'components'
import LwjTable from 'components/LwjTable/LwjTable'
import {
  balanceChangeType,
  balanceChangeReason,
  balanceChangeStatus
} from 'utils/enumConfig'
import { Modal, Button, Form, Input, Menu, Dropdown, Icon, Card, Tag, message, Popconfirm } from 'antd'
import FormModal from './FormModal'
import AuditModal from './AuditModal'
import ViewModal from './ViewModal'
import SubmitModal from './SubmitModal'
import DistributorList from './DistributorList'
import moment from 'moment'
import styles from './index.less'
import GeneralFilter from 'components/Filter/GeneralFilter'
import { showButton } from 'utils/promissionFilter'
import OrderFilterUnExpand from 'components/Filter/OrderFilterUnExpand'

const CheckableTag = Tag.CheckableTag
const table = ({location, dispatch, balanceChangeApply, app, loading}) => {
  const {
    items,
    currentItem,
    pagination,
    formModalVisible,
    auditModalVisible,
    viewModalVisible,
    submitModalVisible,
    selectedTags,
    isExpand,
    contractNumVisible,
    distributorState: {
      items: distributorItems,
      pagination: distributorPagination,
      distributorModalVisible,
      currentItem: distributorItem
    }
  } = balanceChangeApply

  const {user, resources} = app

  const balanceChangeReasonFilter = () => {
    let option = [
      {
        value: '',
        name: '全部'
      },
    ]

    Object.keys(balanceChangeReason).forEach(key => {
      option.push({
        value: key,
        name: balanceChangeReason[key]
      })
    })

    return option
  }

  const breadcrumbList = [
    {
      title: '财务管理'
    },
    {
      title: '余额变更'
    },
  ]

  /**
   * 定义筛选属性 表单相关
   * @type {{filterItems: *[], onFilterChange(*): void}}
   */
  const filterProps = {
    filterItems: [
      {
        type: 'input',
        id: 'distributorName',
        title: '门店名称',
        placeholder: '门店名称'
      }, {
        type: 'select',
        id: 'reason',
        title: '变更原因',
        options: balanceChangeReasonFilter()
      }, {
        type: 'input',
        id: 'memo',
        title: '备注',
      },{
        type: 'dateRule',
        id: 'createTime',
        dateFormat: 'YYYY/MM/DD HH:mm:ss',
        title: '申请时间'
      }
    ],
    isExpand,
    noExpand() {
      dispatch({ type: 'balanceChangeApply/unExpandFilter', payload: {} })
    },
    expand() {
      dispatch({ type: 'balanceChangeApply/expandFilter', payload: {} })
    },
    onFilterChange(value) {
      dispatch({
        type: 'balanceChangeApply/query',
        payload: {
          ...value
        }
      })
    }
  }

  /**
   * 重置标签方法
   */
  const resetSelectTags = () => {
    dispatch({
      type: 'balanceChangeApply/queryBySelectedTags',
      payload: {
        selectedTags: []
      }
    })
  }

  const onAudit = (record) => {
    dispatch({
      type: 'balanceChangeApply/openAuditModal',
      payload: record
    })
  }
  const onEdit = (record) => {
    dispatch({
      type: 'balanceChangeApply/openFormModal',
      payload: record
    })
  }
  const onView = (record) => {
    dispatch({
      type: 'balanceChangeApply/showViewModal',
      payload: record
    })
  }

  const onSubmit = (record) => {
    dispatch({
      type: 'balanceChangeApply/showSubmitModal',
      payload: record
    })
  }

  const tableProps = {
    dataSource: items,
    pagination: pagination,
    loading: loading.effects['balanceChangeApply/query'],
    pageChangeAction: 'balanceChangeApply/query',
    dispatch,
    location,
    columns: [
      // {
      //   title: '序号',
      //   key: 'index',
      //   render: (text, record, index) => (
      //     <span>
      //       {index + 1}
      //     </span>
      //   )
      // },
      {
        title: '门店名称',
        dataIndex: 'distributorName',
        key: 'distributorName',
      }, {
        title: '变更原因',
        dataIndex: 'reason',
        key: 'reason',
        render: (text, record) => (
          <span>
            {balanceChangeReason[text]}
          </span>
        )
      }, {
        title: '变更金额',
        dataIndex: 'changingAmount',
        key: 'changingAmount',
        render: (text, record) => (
          <span style={record.type === 'BALANCE_LESS' ? { color: 'red' } : { color: 'green' }}>
            {text}
          </span>
        )
      }, {
        title: '申请人',
        dataIndex: 'userName',
        key: 'userName',
      }, {
        title: '申请时间',
        dataIndex: 'createTime',
        key: 'createTime',
        render: (text, record, index) => (moment(text).format('YYYY-MM-DD HH:mm:ss'))
      }, {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
        width: 300,
        render: (text, record, index) => (<span>{record.reasonKeywords}，{text}</span>)
      }, {
        title: '审核状态',
        dataIndex: 'status',
        key: 'status',
        render: (text, record) => (
          <span>
            {balanceChangeStatus[text]}
          </span>
        ),
      }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          record.status === 'AUDIT_STAY' && showButton('balanceChangeApply.audit', resources, user) ? <span><a onClick={() => onAudit(record)}> 审核 </a></span> :
            record.status === 'DRAFT' ? <div><span><a
              onClick={() => onEdit(record)}> 编辑 </a></span>
              <span>
                <a onClick={() => onSubmit(record)}> 提交 </a>
              </span>
              <span>
                <Popconfirm title="确认取消" onConfirm={() => {
                  dispatch({
                    type: 'balanceChangeApply/cancel',
                    payload: record
                  })
                }} okText="是" cancelText="否">
                  <a> 取消 </a>
                </Popconfirm>
              </span>
            </div> : <span><a
              onClick={() => onView(record)}> 查看 </a></span>
        )
      }
    ]
  }

  const formModalProps = {
    title: '金额变更',
    visible: formModalVisible,
    item: currentItem,
    onOk: (data) => {
      if ('id' in currentItem) {
        data.id = currentItem.id
        data.version = currentItem.version
        dispatch({
          type: 'balanceChangeApply/update',
          payload: data
        })
      } else {
        data.distributorId = currentItem.distributorId
        if (_.isEmpty(data.distributorId)) {
          message.warning('请选择门店')
          return
        }
        dispatch({
          type: 'balanceChangeApply/store',
          payload: data
        })
      }

      setTimeout(() => {
        dispatch({
          type: 'balanceChangeApply/query',
          payload: {
            isTablePagination: true
          }
        })
      }, 1000)
    },
    confirmLoading: false,
    onCancel: () => {
      dispatch({
        type: 'balanceChangeApply/hideModal',
        payload: {}
      })
    },
    destroyOnClose: true,
    width: 1200,
    dispatch,
    distributorItem,
    contractNumVisible
  }

  const distributorModalProps = {
    title: '门店选择',
    visible: distributorModalVisible,
    item: distributorItems,
    footer: null,
    onOk: (data) => {
      console.log(data)
    },
    confirmLoading: false,
    onCancel: () => {
      dispatch({
        type: 'balanceChangeApply/hideDistributorModal',
        payload: {}
      })
    },
    destroyOnClose: true,
    width: 1200,
    dispatch,
    tableProps: {
      onSelectRows: (id, data) => {
        dispatch({
          type: 'balanceChangeApply/setDistributor',
          payload: data
        })
        dispatch({
          type: 'balanceChangeApply/hideDistributorModal',
          payload: {}
        })
      },
      onRowClick: (datum) => {
        dispatch({
          type: 'balanceChangeApply/setDistributor',
          payload: datum
        })
        dispatch({
          type: 'balanceChangeApply/hideDistributorModal',
          payload: {}
        })
      },
      dataSource: distributorItems,
      pagination: distributorPagination,
      loading: loading.effects['balanceChangeApply/distributorQuery'],
      pageChangeAction: 'balanceChangeApply/distributorQuery',
      selectedRowKeys: [distributorItem.id],
      dispatch
    }
  }

  const auditModalProps = {
    title: '审核变更',
    visible: auditModalVisible,
    currentItem,
    distributorItem,
    footer: false,
    confirmLoading: false,
    destroyOnClose: true,
    width: 1200,
    dispatch,
    onCancel: () => {
      dispatch({
        type: 'balanceChangeApply/hideModal',
        payload: {}
      })
    },
  }

  const viewModalProps = {
    title: '查看变更',
    visible: viewModalVisible,
    currentItem,
    distributorItem,
    confirmLoading: false,
    destroyOnClose: true,
    width: 1200,
    dispatch,
    onCancel: () => {
      dispatch({
        type: 'balanceChangeApply/hideModal',
        payload: {}
      })
    },
    onOk: () => {
      dispatch({
        type: 'balanceChangeApply/hideModal',
        payload: {}
      })
    },
  }

  const submitModalProps = {
    title: '提交余额变更',
    visible: submitModalVisible,
    currentItem,
    distributorItem,
    confirmLoading: false,
    destroyOnClose: true,
    width: 1200,
    dispatch,
    onCancel: () => {
      dispatch({
        type: 'balanceChangeApply/hideModal',
        payload: {}
      })
    },
  }

  /**
   * 选中标签方法
   * @param {*} tag
   * @param {*} checked
   */
  const handleChange = (tag, checked) => {
    const nextSelectedTags = checked ?
      [...selectedTags, tag] :
      selectedTags.filter(t => t !== tag)
    dispatch({
      type: 'balanceChangeApply/queryBySelectedTags',
      payload: {
        selectedTags: nextSelectedTags
      }
    })
  }

  const statusTagBuilder = () => {
    let tags = []
    Object.keys(balanceChangeStatus).forEach((key) => {
      tags.push(<CheckableTag
        color="#2db7f5"
        key={key}
        checked={selectedTags.indexOf(key) > -1}
        onChange={checked => handleChange(key, checked)}
      >
        {balanceChangeStatus[key]}
      </CheckableTag>)
    })

    return tags
  }

  const onCreateModal = () => {
    dispatch({
      type: 'balanceChangeApply/showFormModal',
      payload: {}
    })
  }

  return (
    <PageHeaderLayout title='余额变更' breadcrumbList={breadcrumbList}>
      <Page inner>
        <OrderFilterUnExpand {...filterProps} />
        <div style={{
          textAlign: 'left',
          marginBottom: 20
        }}>
          {showButton('balanceChangeApply.apply', resources, user) && <Button
            type="primary"
            className={styles.card}
            onClick={onCreateModal}
          >
            余额变更申请
          </Button>}
        </div>
        <div style={{ marginBottom: 10 }}>
          <Card type="inner">
            <h6 style={{ marginRight: 8, display: 'inline' }}>审核状态:</h6>
            {statusTagBuilder()}
            <Button type="primary" size="small" onClick={() => resetSelectTags()}>重置</Button>
          </Card>
        </div>
        <LwjTable {...tableProps} />
        {formModalVisible && <FormModal {...formModalProps} />}
        {distributorModalVisible && <DistributorList {...distributorModalProps} />}
        {auditModalVisible && <AuditModal {...auditModalProps} />}
        {viewModalVisible && <ViewModal {...viewModalProps} />}
        {submitModalVisible && <SubmitModal {...submitModalProps} />}
      </Page>
    </PageHeaderLayout>
  )
}

export default connect(({balanceChangeApply, app, loading}) => ({
  balanceChangeApply,
  app,
  loading
}))(table)
